from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from rest_framework.decorators import action
from rest_framework.authentication import BasicAuthentication, SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.throttling import UserRateThrottle
from rest_framework.filters import OrderingFilter
from rest_framework.pagination import PageNumberPagination

from .models import BookInfo
from .serializer import BookSerializer


class PageNum(PageNumberPagination):
    """自定义分页器"""
    page_size_query_param = 'page_size'  # 指定控制每页数量的参数
    max_page_size = 6  # 指定每页最大返回数量


class BooksView(ModelViewSet):
    """获取所有图书、保存图书"""

    print("111-----")
    # 只针对个别视图的认证和权限
    # authentication_classes = (BasicAuthentication, SessionAuthentication)
    # 权限
    # permission_classes = (IsAuthenticated,)
    # 用户限流
    # throttle_classes = (UserRateThrottle,)
    # 限流
    throttle_scope = 'get_books'
    # 指定过滤字段
    filter_fields = ('name', 'readcount')
    # 指定排序字段
    ordering_fields = ('readcount', 'id')  # TODO 没效果啊
    # 指定分页器
    pagination_class = PageNum


    queryset = BookInfo.objects.all()  # 指定当前类视图使用的查询集数据
    # serializer_class = BookSerializer  # 指定当前类视图使用的序列化器

    def get_serializer_class(self):
        """为了给不同方法指定不同的序列化器，重写该方法"""
        if self.action == 'lastdata':
            return BookSerializer
        else:
            return BookSerializer  # 可以指定不同的序列化器

    @action(methods=['get'], detail=True)  # detail=True会匹配pk，如果=False 不会匹配，此处methods=['get'] 实际是调用list方法
    def lastdata(self, request, pk):
        """自定义方法名"""
        print(self.action)  # 打印 "lastdata"，其实是指向方法名
        book = BookInfo.objects.get(id=pk)

        ser = BookSerializer(book)

        return Response(ser.data)


# class BookView(ModelViewSet):
#     """获取单一图书、更新图书、删除图书"""
#
#     queryset = BookInfo.objects.all()  # 指定当前类视图使用的查询集数据
#     serializer_class = BookSerializer  # 指定当前类视图使用的序列化器
#
#     @action(methods=['get'], detail=True)  # detail=True会匹配pk，如果=False 不会匹配
#     def lastdata(self, request, pk):
#         """自定义方法名"""
#         book = BookInfo.objects.get(id=pk)
#
#         ser = BookSerializer(book)
#
#         return Response(ser.data)


